from django.shortcuts import render
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import serializers
from rest_framework.views import APIView
from drf_yasg.utils import swagger_auto_schema
from rest_framework.parsers import FormParser
from rest_framework.decorators import parser_classes, permission_classes
from drf_yasg import openapi
from dvadmin.utils.serializers import CustomModelSerializer
from dvadmin.utils.json_response import SuccessResponse, DetailResponse, ErrorResponse
from dvadmin.utils.viewset import CustomModelViewSet
from .dag.graph import Node, Edge, Graph
from .models import GraphInfo
from .dag.executer import CVExecuter
from scheduling.paradag import dag_run, SequentialProcessor
import json

# class NodeInfoSerializer(CustomModelSerializer):
#     class Meta:
#         model = NodeInfo
#         fields = "__all__"
#         read_only_fields = ["id"]
# 
# class EdgeInfoSerializer(CustomModelSerializer):
#     class Meta:
#         model = EdgeInfo
#         fields = "__all__"
#         read_only_fields = ["id"]

class GraphInfoSerializer(CustomModelSerializer):
    class Meta:
        model = GraphInfo
        fields = "__all__"
        read_only_fields = ["id"]

# Create your views here.
@swagger_auto_schema(
    method='post',
    request_body=openapi.Schema(
        type=openapi.TYPE_OBJECT,
        required=['img','operations'],
        properties={
            'nodes': openapi.Schema(type=openapi.TYPE_OBJECT),
            'params': openapi.Schema(type=openapi.TYPE_OBJECT)
        },
    ),
    operation_description='Create an events'
)
@api_view(["POST"])
@permission_classes([])
def executeDAG(request):
    if request.method == "POST":
        nodes_data = json.loads(request.data["nodes"])
        edges_data = json.loads(request.data["edges"])
        nodes_map = {}
        edges = []
        for n in nodes_data:
            if(n['isTrue']):
                node = Node(n['id'], n['name'], n['params'], should_execute=n['isTrue'])
            else:
                node = Node(n['id'], n['name'], n['params'], should_execute=True)
            nodes_map[n['id']] = node
        for e in edges_data:
            edges.append(Edge(e['source'], e['target']))
        graph = Graph(nodes_map, edges)
        dag_run(graph.graph, processor=SequentialProcessor(), executor=CVExecuter())
        return SuccessResponse()


class GraphInfoViewSet(CustomModelViewSet):
    queryset = GraphInfo.objects.all()
    serializer_class = GraphInfoSerializer
